defmodule ProgContestWeb.QuizController do
  use ProgContestWeb, :controller

  alias ProgContest.Quizzes

  def index(conn, %{"contest_id" => contest_id}) do
    json(conn, Quizzes.list_quizzes(contest_id))
  end

  def show(conn, %{"id" => id}) do
    json(conn, Quizzes.get_quiz!(id))
  end

  def create(conn, %{"contest_id" => contest_id, "quiz" => quiz_params}) do
    case Quizzes.create_quiz(Map.put(quiz_params, "contest_id", contest_id)) do
      {:ok, quiz} ->
        conn
        |> put_status(201)
        |> json(quiz)
      {:error, changeset} ->
        conn
        |> put_status(400)
        |> errors(changeset)
    end
  end

  def update(conn, %{"id" => id, "quiz" => quiz_params}) do
    case id |> Quizzes.get_quiz!() |> Quizzes.update_quiz(quiz_params) do
      {:ok, quiz} -> json(conn, quiz)
      {:error, changeset} -> errors(conn, changeset)
    end
  end

  def delete(conn, %{"id" => id}) do
    case id |> Quizzes.get_quiz!() |> Quizzes.delete_quiz() do
      {:ok, _} -> send_resp(conn, 204, "")
      {:error, changeset} -> errors(conn, changeset)
    end
  end
end
